//--------简单的显示对象动画-----------------
/**
 * 其它优秀的引擎库
 * https://ecomfe.github.io/zrender-doc/public/
 * 图表生成 https://echarts.apache.org/examples/zh/index.html
 * https://p5js.org/zh-Hans/get-started/
 * https://github.com/CreateJS/EaselJS
 */
/**
使用说明 
	var moonjs=new MoonJs();
	moonjs.init(canvas);//初始化或者使用moonjs.init(moonjs.createCanvas({c:'#999'}));
	let rect=moonjs.createDisplay('rect');//创建方形，锚点在左上角
	let rect=moonjs.createDisplay('roundRect');//创建圆角方形，锚点在左上角
    let rect2=moonjs.createDisplay('polygon')//创建正方形，锚点在中间(拖动操作首选)
    let polygon=moonjs.createDisplay('polygon').setPolygon(n)//创建多边形，锚点在中间，n需要大于等于3
	let circle=moonjs.createDisplay('circle');//创建圆形，锚点在中间
	let circle=moonjs.createDisplay('arc');//创建弧形，锚点在中间
	let image=moonjs.createDisplay('image').createImage(url);//创建图片，锚点在左上角,url图片地址
	image.setAnchorXY(x,y)//修改锚点位置，目前只对rect与image有作用
    moonjs.createDisplay('polygon').setSides([[0,-40],[10,0],[0,40],[-10,0],[0,-40]]);//创建多边形任意形状
    moonjs.createDisplay('line');//创建线条,x,y表示起点位置w,h表示结束位置
	moonjs.createDisplay('font').setText('文字内容').setFont(`20px 微软雅黑`);
	moonjs.start();//开始渲染
	moonjs.update=()=>{
		rect.x++;
		circle.y++;
		image.x++;
	}
    moonjs.click(rect,(o)=>{console.log(o.x)},2);//双击
    moonjs.startDrag((o)=>{console.log(o.id)})//拖动
	moonjs.createSound('../rec/sound/bg.mp3');//创建声音
* author:ywx620
* web:https://ywx620.gitee.io/learn/
*/
//尽量不要在外部实例化
class Mj_Display {
	//构造函数
	constructor(id,type) {
		this.type=type;
		this.id=id;
		this.font="12px Arial";
		this.text='';
		this.name='none';
		this.childs=[];
		//r表示圆半径,z为z轴既渲染先后,a为角度多边形用到	
		[this.a,this.x,this.y,this.z,this.w,this.h,this.r,this.color,this.scale,this.scaleX,this.scaleY,this.alpha,this.lineWidth]=[0,0,0,0,40,40,20,'#ff0000',1,1,1,1];	
		//rx,ry表示椭圆x与y轴半半径
		[this.rx,this.ry]=[40,20];
		//锚点位置
		[this.anchorX,this.anchorY]=[0.5,0.5];
	}
	addChild(child){
		child.parent=this;
		this.childs.push(child);
	}
	removeChild(child){
		let i=this.childs.indexOf(child);
		if(i>0) this.childs.splice(i,1);
	}
	removeAllChild(){
		if(this.childs.length>0) this.removeChild(this.childs[i]);
	}
	//删除自己
	removeSelf(){
		this._removeSelf=true;
	}
	//设置多边形
	setPolygon(t=3,r,a){
		if(this.isOutSides) return this;//已经设置过外部数据，就不在处理下面内容
		if(!isNaN(r)) this.r=r;//是数值类型才赋值
		if(isNaN(a)) a=0;//不是数值类型默认为0
		let sides=[];
		let angle=0;
		for (let i=0; i <= t; ++i) {
			sides.push([(this.r * Math.sin(angle+a)),(this.r * Math.cos(angle+a))]);
			angle += 2*Math.PI/t;
		}
		this.sideNum=t;
		this.sides=sides;
		return this;
	}
	//设置任意形状（用户在外部自己定义）
	setSides(sides){
		this.isOutSides=true;//表示外部设置的边
		this.sides=sides;
		return this;
	}
	//创建图形
	createImage=(url)=>{
		let image = document.createElement('img');
		image.src = url;
		image.onload = ()=>{this.hasImage=true};
		this.image=image;
		return this;
	}
	//设置多边形的尺寸大小
	setPolygonSize(r){
		(this.sideNum>=3)&&this.setPolygon(this.sideNum,r);
		return this;
	}
	//通过对象来设置位置
	setPoint(p){
		if(p){
			this.x=p.x||this.x;
			this.y=p.y||this.y;
		}
		return this;
	}
	//设置大小比例
	setScale(s){
		this.scaleX=s;
		this.scaleY=s;
		return this;
	}
	//设置大小比例
	setScaleXY(x,y){
		this.scaleX=x||1;
		this.scaleY=y||1;
		return this;
	}
	//设置宽高
	setWH(w,h){
		if(isNaN(w)) w=10;
		if(isNaN(h)) h=10;
		this.w=w;
		this.h=h;
		return this;
	}
	set width(v){this.w=v;}
	get width(){return this.w;}
	set height(v){this.h=v;}
	get height(){return this.h;}
	//设置颜色
	setColor(c){
		this.color=c;
		return this;
	}
	//设置透明度
	setAlpha(a){
		this.alpha=a;
		return this;
	}
	//设置半径
	setRadius(r){
		this.r=r;
		return this;
	}
	set radius(v){this.radius=v;}
	get radius(){return this.radius;}
	//设置椭圆x与y半径
	setRadiusXY(rx,ry){
		this.rx=rx;
		this.ry=ry;
		return this;s
	}
	//设置角度
	setAngle(a){
		this.a=a;
		return this;
	}
	set angle(v){this.a=v;}
	get angle(){return this.a;}
	//设置位置this.text
	setXY(x,y){
		this.x=x||this.x;
		this.y=y||this.y;
		return this;
	}
	//设置锚点 目前只对rect与image有作用
	setAnchorXY(x,y){
		this.anchorX=x;
		this.anchorY=y;
		return this;
	}
	/**设置z轴,值越大,显示越在上面*/
	setZ(z){
		this.z=z;
		return this;
	}
	//设置文本内容
	setText(t){
		this.text=t;
		return this;
	}
	setArcSarEnd(sar,end){
		this.acrSar=sar;
		this.acrEnd=end;
		return this;
	}
	//设置文本字号与字体 setFont("30px Arial")
	setFont(f){
		this.font=f;
		return this;
	}
	//设置外边框,sideColor边框颜色,sideSize边框厚度,sideType边框类型1为只有边框,2为有边框有填充
	setOutSide(sideColor='#000',sideSize=2,sideType=1){
		this.sideColor=sideColor;
		this.sideSize=sideSize;
		this.sideType=sideType;
		return this;
	}
	//鼠标与图形碰撞检测
	hitPoint(x,y){
		//这个是左上角是锚点，弃用，目前都锚点都在中心
		if(this.type==='circle'||this.type==='polygon'){
			x=x-this.x; y=y-this.y;
			if(Math.hypot(x,y)<this.r) return true;
		}if(this.type==='rect'||this.type==='roundRect'||this.type==='image'||this.type==='font'){
			let [tx,ty,tw,th]=[this.x-this.w/2,this.y-this.h/2,this.x+this.w/2,this.y+this.h/2]
			if(x>=tx&&x<=tw&&y>=ty&&y<=th) return true;
		}
		return false;
	}
	//两个图形目标的碰撞检测
	hitTarget(target,tr){
		let [t1,t2]=[this,target];
		if(t1.type==='polygon'&&t2.type==='polygon'
		||t1.type==='circle'&&t2.type==='circle'
		||t1.type==='polygon'&&t2.type==='circle'
		||t1.type==='circle'&&t2.type==='polygon'
		){
			let [x,y,r]=[t1.x-t2.x,t1.y-t2.y,t1.r*t1.scale+t2.r*t2.scale];
			r=tr||r;
			if(Math.hypot(x,y)<r) return true;
			else                  return false;
		}
		return false;//其它类型碰撞暂时不做
	}
	//帧听事件
	on(eventName,callBack){
		MoonJs.on(eventName,callBack);
	}
	//发布事件
	emit(eventName,data){
		MoonJs.emit(eventName,data);
	}
	//删除事件
	off(eventName,callBack){
		MoonJs.off(eventName,callBack);
	}
}
class Mj_Sound{
	constructor(url) {
		//<audio id='sound_di' controls="controls" autobuffer="autobuffer" hidden="true"></audio>
		let audio = document.createElement('audio');
		audio.src = url;
		audio.hidden="true";
		audio.autoplay='true';
		document.body.appendChild(audio);
		this.audio=audio;
	}
	play(){				this.audio.play();	}
	pause(){			this.audio.pause();	}
	set volume(value){	this.audio.volume=value;}
	get volume(){return this.audio.volume;}
	set src(url){       this.autio.src=url;}
	get src(){   return this.autio.src;}
	setUrl(url){this.audio.src=url}
}
class MoonJs{
	constructor() {
		//console.log('this',this)
		this.id=1;
		this.z=1;
	}
	//初始化
	init(canvas){
		this.clear();
		this.id=1;
		this.z=0;
		this.canvas=canvas;
		this.context=canvas.getContext("2d");
		this.map=new Map();
		this.timeId=0;
		this.clearTime=0;
		this.isPlay=false;
	}
	//创建canvas 全屏需要设置 body { margin: 0;}
	createCanvas({w=0,h=0,c='#ffffff'}){
		w=w||window.innerWidth;
		h=h||window.innerHeight;
		var canvas = document.createElement('canvas');
		canvas.style.position='absolute';//不受任何限制的，位置可自由变动
		document.body.appendChild(canvas);
		canvas.width = w;
		canvas.height = h;
		canvas.style.backgroundColor = c;
		return canvas
	}
	createCanvasByMobile(){
		let canvas=this.createCanvas({})
		let [w,h]=[window.innerWidth,window.innerHeight]
		canvas.height=h;
		if(Unify.isMobile()){//移动设置上
			canvas.width=w;
		}else{
			canvas.width=h/2;
			canvas.style.left=`${(w-canvas.width)/2}px`;
		}
		return canvas;
	}
	clear(){
		this.stop();
		this.canvas=null;
		this.context=null;
		this.map=null;
	}
	//创建形状
	createDisplay(type){
		let id=++this.id;
		this.z=id;
		let o=new Mj_Display(id,type)
		this.map.set(id,o);
		return this.map.get(id);
	}
	createSound(url){
		let sound=new Mj_Sound(url);
		return sound;
	}
	//得到世界Z轴最高一级
	worldZ(){
		return ++this.z;
	}
	//开始,默认的刷屏率是每秒60帧(1000/60)
	start(t=16.66){
		this.stop()
		this.timeId=t;
		this.isPlay=true;
		this.clearTime=setInterval(this.render.bind(this),this.timeId);
		this.renderTime=(new Date).valueOf();
		this.render();
	}
	//停止
	stop(){
		clearInterval(this.clearTime);
		this.isPlay=false;
	}
	//随机整数
	randomInt(t=10,s=1){
		return Math.round(Math.random()*(t-s))+s;
	}
	//随机颜色
	get randomColor(){
		let c='#';
		for(let i=0;i<3;i++)c+=Number(Math.random()*255).toString(16).split('.')[0];
		c+='000';c=c.substring(0,7);//可能出现不够位数的情况，所以加了几个0再取前7位数。
		return c;
	}
	//单击或是双击（type=1单击，type=2双击）
	click(target,callBack,type=1){
		let canvas=this.canvas;
		let thisObj=this;
		if(type==1){//单击
			canvas.removeEventListener("click",onClick,false);
			canvas.addEventListener("click",onClick,false);
		}else{//双击
			canvas.removeEventListener("dblclick",onClick,false);
			canvas.addEventListener('dblclick',onClick,false);
		}
		function onClick(e){
			let [x,y]=thisObj.getMouseXY(e);
			if(target.hitPoint(x,y)){
				target.z=thisObj.worldZ();
				callBack&&callBack(target);
			}
		}
	}
	mouseDown(target,callBack){
		let canvas=this.canvas;
		let thisObj=this;
		canvas.removeEventListener("mousedown",onMouseHandler,false);
		canvas.addEventListener("mousedown",onMouseHandler,false);
		function onMouseHandler(e){
			e.stopPropagation();
			let [x,y]=thisObj.getMouseXY(e);
			if(target.hitPoint(x,y)){
				target.z=thisObj.worldZ();
				callBack&&callBack(target);
			}
		}
	}
	mouseUp(target,callBack){
		let canvas=this.canvas;
		let thisObj=this;
		canvas.removeEventListener("mouseup",onMouseHandler,false);
		canvas.addEventListener("mouseup",onMouseHandler,false);
		function onMouseHandler(e){
			e.stopPropagation();
			let [x,y]=thisObj.getMouseXY(e);
			if(target.hitPoint(x,y)){
				target.z=thisObj.worldZ();
				callBack&&callBack(target);
			}
		}
	}
	mouseMove(target,callBack){
		let canvas=this.canvas;
		let thisObj=this;
		canvas.removeEventListener("mousemove",onMouseHandler,false);
		canvas.addEventListener("mousemove",onMouseHandler,false);
		function onMouseHandler(e){
			let [x,y]=thisObj.getMouseXY(e);
			if(target.hitPoint(x,y)){
				target.z=thisObj.worldZ();
				callBack&&callBack(target);
			}
		}
	}
	touchStartEnd(target,cbStart,cbEnd){
		document.removeEventListener('touchstart',onTouchStart, false);
		document.removeEventListener('touchend',onTouchStart, false);
		document.addEventListener('touchstart',onTouchStart, false);
		document.addEventListener('touchend',onTouchEnd, false);
		let thisObj=this;
		let tp={x:0,y:0}
		function onTouchStart(e){
			let ts=e.touches;
			if(ts.length==0||ts.length>=2){//不支持没有和多个手指触控操作
				return;
			}
			[tp.x,tp.y]=[ts[0].clientX,ts[0].clientY];
			if(target.hitPoint(tp.x,tp.y)){
				target.z=thisObj.worldZ();
				cbStart&&cbStart(target);
			}
		}
		function onTouchEnd(e){
			if(target.hitPoint(tp.x,tp.y)){
				cbEnd&&cbEnd(target);
			}
		}
	}
	/**鼠标手指触控（是用于移动还是PC内部控制）*/
	mouseTouch(target,cbStart,cbEnd){
		if(Unify.isMobile()){
			this.touchStartEnd(target,cbStart,cbEnd);
		}else{
			this.mouseDown(target,cbStart);
			this.mouseUp(target,cbEnd);
		}
	}
	//暂停拖动
	setPauseDrag(boo){
		this.pauseDrag=boo;
	}
	//设置xy轴上的偏移量
	setGapXY(x,y){
		this.gapx=x;
		this.gapy=y;
	}
	/**得到鼠标点下的坐标*/
	getMouseXY(e){
		let [gx,gy]=[this.gapx||0,this.gapy||0];
		return [e.layerX+gx,e.layerY+gy];
	}
	/**删除拖动目标对象*/
	removeDragTarget(target){
		if(!this.dragTargets)this.dragTargets=[];
		this.dragTargets.push(target);
	}
	//开始拖动所有对象(callBack是停止拖动的回调)
	startDrag(callBack){
		let canvas=this.canvas;
		let target;
		let thisObj=this;
		canvas.removeEventListener("mousedown",doMouseDown,false);//防止多次被调用
		canvas.addEventListener("mousedown",doMouseDown,false);
		function doMouseDown(e){
			if(!thisObj.pauseDrag){
				let [x,y]=thisObj.getMouseXY(e);
				canvas.addEventListener('mousemove', doMouseMove,false);
				canvas.addEventListener('mouseup',  doMouseUp, false);
				for(let o of thisObj.map.values()){
					if(o.hitPoint(x,y)){
						if(thisObj.dragTargets){
							if(thisObj.dragTargets.indexOf(o)>=0){
								return;
							}
						}
						target=o;
						target.startX=x-target.x;
						target.startY=y-target.y;
						target.z=thisObj.worldZ();
						thisObj.dragDownCb&&thisObj.dragDownCb(target);
						break;
					}
				}
			}
		}
		function doMouseMove(e){
			let [x,y]=thisObj.getMouseXY(e);
			if(target){
				x-=target.startX;
				y-=target.startY;
				target.setXY(x,y);
				thisObj.dragMoveCb&&thisObj.dragMoveCb(target);
			}
		}
		function doMouseUp(e){
			canvas.removeEventListener('mousemove', doMouseMove,false);
			canvas.removeEventListener('mouseup',  doMouseUp, false);
			callBack&&callBack(target);
			this.dragUpCb&&this.dragUpCb(target);
			target=null;
		}
	}
	//停止拖动
	stopDrag(){
		let canvas=this.canvas;
		canvas.removeEventListener("mousedown",doMouseDown,false);
	}
	removeKeyboard(keyDownCb,keyUpCb){
		window.removeEventListener('keydown', keyDownCb,true);
		window.removeEventListener('keyup', keyUpCb,true);
	}
	addKeyboard(keyDownCb,keyUpCb){
		this.removeKeyboard(keyDownCb,keyUpCb)
		window.addEventListener('keydown', keyDownCb,true);
		window.addEventListener('keyup', keyUpCb,true);
	}
	//字母转小写
	keyToLower(s){
		return s.toLocaleLowerCase();
	}
	//渲染
	render(){
		if(this.isPlay){
			if(this.renderCount>20000){
				console.warn('数量超过了20000个，为了你的CPU考虑请减少数量。')
				return;
			}
			let cxt=this.context;
			cxt.clearRect(0, 0, this.canvas.width, this.canvas.height);
			let values=[];
			for(let o of this.map.values())values.push(o);
			values.sort((a,b)=>a.z-b.z);
			for(let o of values){
				if(o._removeSelf){
					this.map.delete(o.id);
					continue;
				}
				this.startRender(cxt,o);
			}
			let time=(new Date).valueOf();
			let dt=time-this.renderTime;
			this.renderTime=time;
			this.update&&this.update(dt/100);
		}
	}
	startRender(cxt,o){
		if(!o.parent) this.renderChild(cxt,o);
		let len=o.childs.length;
		if(len>0){//绘制子级对象（未解决问题1目前只有两级绘制2最后一个会变黑色）
			for(let i=0;i<len;i++){
				let child=o.childs[i];
				this.renderChild(cxt,child);
				cxt.closePath();
				if(child.sideType!==1) cxt.fill();
				cxt.restore(); 
			}
		}
		cxt.closePath();
		if(o.sideType!==1) cxt.fill();
		cxt.restore(); 
	}
	angleToRadian(angle){
		return angle*Math.PI/180;
	}
	renderChild(cxt,o){
		let w=o.w;
		let h=o.h;
		cxt.save();
		cxt.translate(o.x,o.y);
		cxt.rotate(o.a*Math.PI/180);
		cxt.scale(o.scaleX,o.scaleY);
		cxt.beginPath();
		cxt.globalAlpha = o.alpha>0?o.alpha:0;
		cxt.fillStyle=o.color;
		if(o.sideType){
			cxt.strokeStyle=o.sideColor;
			cxt.lineWidth=o.sideSize;
		}
		switch(o.type){
			case 'rect'://方形
				cxt.fillRect(-w*o.anchorX,-h*o.anchorY,w,h);
			break;
			case 'roundRect'://圆角矩形
				cxt.roundRect(-w*o.anchorX,-h*o.anchorY,w,h, o.r||10);
				cxt.fill();
			case 'circle'://圆形
				var max=o.maxAngle||360;
				max=max*Math.PI/180;
				cxt.arc(0,0,o.r,0,max,true);
			break;
			case 'arc'://画弧度
				let [sar,end]=[this.angleToRadian(o.acrSar||0),this.angleToRadian(o.acrEnd||45)];
				cxt.moveTo(0,0);
				cxt.arc(0,0,o.r,sar,end);
			break;
			case 'ellipse'://椭圆
				var max=o.maxAngle||Math.PI * 2;
				cxt.ellipse(0, 0, o.rx, o.ry, 0, 0, max);
			break;
			case 'line'://直线
				if(cxt.globalAlpha>=1){
					cxt.strokeStyle=o.color;
					cxt.lineWidth=o.lineWidth||1;
					cxt.moveTo(0,0);
					cxt.lineTo(o.w,o.h);
					cxt.stroke();
				}
				break;
			case 'polygon'://多边形
				let sides=o.sides||o.setPolygon().sides;
				cxt.strokeStyle=o.color;
				cxt.lineWidth=0.01;//小到看不见这些线
				cxt.moveTo(0,0);
				for(let side of sides){
					let [x,y]=side;
					cxt.lineTo(x,y);
				}
				cxt.stroke();
				break;
			case 'image'://图形
				if(o.hasImage){
					w=o.image.width;
					h=o.image.height;
					cxt.drawImage(o.image,-w*o.anchorX,-h*o.anchorY,w,h);
				}
			break;
			case 'tiles'://瓦块
				if(o.hasImage){
					cxt.drawImage(o.image,o.imageData.x,o.imageData.y,o.imageData.w,o.imageData.h,0,0,o.imageData.w,o.imageData.h);
				}
			case 'animation'://动画
				if(o.hasAni){
					let ani=o.ani;
					if(ani.dt%ani.time===0){
						ani.dt=0;
						ani.index++;
						if(ani.index===ani.datas.length) ani.index=0;
					}
					ani.dt++;
					let a=ani.datas[ani.index];
					cxt.drawImage(o.image,a.x,a.y,a.w,a.h,0,0,a.w,a.h);
				}
				break;
			case 'font':
				if(o.textAlign) cxt.textAlign=o.textAlign;
				else			cxt.textAlign = "center";
				cxt.font=o.font;
				cxt.fillText(o.text,0,0);//子乐紫恩
				
			break;
		}
		if(o.sideType){
			cxt.stroke();
		}
	}
	//如果超出边境则删除，只做中心点判断，如果要精准判断请自行处理
	outSideRemove(){
		let s=this.stage;
		for(let o of this.map.values()){
			if(o.x<0||o.x>s.width||o.y<0||o.y>s.height) o.removeSelf();
		}
	}
	//渲染个数
	get renderCount(){
		return this.map.size;
	}
	/**查看是否在x,y点上有对象*/
	checkHasDisplay(x,y){
		for(let o of this.map.values()){
			if(o.hitPoint(x,y)){
				return o;
			}
		}
		return null;
	}
	/**删除所有*/
	removeAll(){
		this.map=new Map();
	}
	//提示
	alert(label,t=3){
		if(this.tipView){
			this.tipView.removeSelf();
			clearTimeout(this.tipView.clearTime);
			this.tipView=null;
		}
		this.tipView=this.createRectText(label,150);
		this.tipView.z=99999;
		this.tipView.setXY(window.innerWidth/2,window.innerHeight/2);
		this.tipView.clearTime=setTimeout(()=>{
			this.tipView.removeSelf();
			this.tipView=null;
		},t*1000);
	}
	createOutside(gapx=0,gapy=0){
		let out=outside;
		out.left+=gapx,out.right-=gapx,out.top+=gapy,out.bottom-=gapy;
		return out
	}
	get outside(){
		return {left:0,top:0,right:this.stage.width,bottom:this.stage.height}
	}
	get stage(){
		return {width:this.canvas.width,height:this.canvas.height}
	}
	get center(){
		return{x:this.stage.width/2,y:this.stage.height/2}
	}
	//-----------------------------事件处理------------------------------------
	static eventContent={};
	//帧听事件
	static on(eventName,callBack){
		if(!MoonJs.eventContent[eventName]){
			MoonJs.eventContent[eventName]=[]
		}
		MoonJs.eventContent[eventName].push(callBack);
	}
	//发布事件
	static emit(eventName,data){
		var a=MoonJs.eventContent[eventName];
		if(a){
			for(var i=0;i<a.length;i++){
				if(data) a[i](data);
				else 	 a[i]();
			}
		}
	}
	//删除事件
	static off(eventName,callBack){
		var a=MoonJs.eventContent[eventName];
		if(a){
			var i=a.indexOf(callBack);
			if(i>=0){
				a.splice(i,1);
			}
		}
	}
	/**删除所有相同名字的事件*/
	static offSameEventName(eventName){
		MoonJs.eventContent[eventName]=null;
	}
	//---------------------------动画与瓦块地图------------------------------
	/**创建瓦块子块
	 * index:所引,cellWidth,cellHeight:子块宽高,num:横排的数量
	*/
	createTilesCell(url,index=1,cellWidth=65,cellHeight=65,num=1){
		let content=this.createDisplay('rect').setWH(0,0);
		for(let i1=0;i1<num;i1++){
			let tiles=this.createDisplay('tiles');
			tiles.x=i1*cellWidth;
			let image = document.createElement('img');
			image.src = url;
			image.onload = ()=>{
				tiles.hasImage=true;
				tiles.image=image;
				let wNum=Math.ceil(image.width/cellWidth);
				let hNum=Math.ceil(image.height/cellHeight);
				let arr=[];
				for(let i=0;i<hNum;i++){
					for(let j=0;j<wNum;j++){
						arr.push([j,i]);
					}
				}
				let [x,y]=[arr[index][0]*cellWidth,arr[index][1]*cellHeight];
				tiles.imageData={x:x,y:y,w:cellWidth,h:cellHeight};	
				content.addChild(tiles);
			};
		}
		return content;
	}
	/**创建瓦块背景，使用子块进行平铺。
	 * cellWidth,cellHeight:子块宽高,n,m:大图索引,xNum,yNum:x轴与y轴数量
	*/
	createTilesBg(url,cellWidth=65,cellHeight=70,n=0,m=1,xNum=10,yNum=5){
		for(var i=0;i<yNum;i++){
		for(let j=0;j<xNum;j++){
			let k=j%2==0?(i%2==0?n:m):(i%2==0?m:n);
			moonjs.createTilesCell(url,k,cellWidth,cellHeight,1).setXY(65*j,70*i);
		}
		}
	}
	/**创建瓦块动画
	 * cellWidth,cellHeight:子块宽高,start,end:动画开始到结束的索引,time:播放速度,值越小速度越快
	*/
	createAnimation(url,start=0,end=1,cellWidth=65,cellHeight=65,time=10){
		let animation=this.createDisplay('animation').setWH(cellWidth,cellHeight);
		let image = document.createElement('img');
		image.src = url;
		image.onload = ()=>{
			animation.hasAni=true;
			animation.image=image;
			let wNum=Math.ceil(image.width/cellWidth);
			let hNum=Math.ceil(image.height/cellHeight);
			console.log(wNum,hNum)
			let arr=[];
			for(let i=0;i<hNum;i++){
				for(let j=0;j<wNum;j++){
					arr.push([j,i]);
				}
			}
			animation.ani={datas:[],time:time,dt:0,index:0};
			for(let i=start;i<end;i++){
				let [x,y]=[arr[i][0]*cellWidth,arr[i][1]*cellHeight];
				let o={x:x,y:y,w:cellWidth,h:cellHeight};
				animation.ani.datas.push(o);
			}
			console.log(animation.ani.datas)
		}
		return animation;
	}
	//-----------------------排版与创建自定义的形状------------------------------
	//排版
	displayRank(array,xNum=1,xDis=0,yDis=0,x=0,y=0,sign=1){
		for(let i=0;i<array.length;i++){
			let display=array[i];
			display.x=x+parseInt(i%xNum)*(display.width+xDis)*sign;
			display.y=y+parseInt(i/xNum)*(display.height+yDis)*sign;
		}
	}
	//创建类似按钮带字符的形状
	createRectText(label,w=100,h=30,lColor='#000',rColor='#F3F3F3',type='rect'){
		let txt=this.createDisplay('font').setXY(0,5).setText(label).setColor(lColor);
		let rect=this.createDisplay(type).setWH(w,h).setColor(rColor);
		rect.addChild(txt);
		rect.t=txt;
		return rect;
	}
	createButton(label,x=0,y=0,callBack){
		let btn=this.createRectText(label);
		[btn.x,btn.y]=[x,y];
		this.click(btn,callBack,1);
		return btn;
	}
	//创建网格
	createWeb({x=0,y=0,w=100,h=100,xNum=10,yNum=10,color='#ffffff',s=1}){
		let [gapx,gapy]=[w/xNum,h/yNum];
		let webs=[];
		for(let i=0;i<=xNum;i++){
			let line=this.createDisplay('line');
			line.lineWidth=s;
			line.color=color;
			line.setXY(x,y+i*gapy);
			line.w=w;
			line.h=0;
			webs.push(line);
		}
		for(let i=0;i<=yNum;i++){
			let line=this.createDisplay('line');
			line.lineWidth=s;
			line.color=color;
			line.setXY(x+i*gapx,y);
			line.w=0;
			line.h=h;
			webs.push(line);
		}
		return webs;
	}
	//创建齿轮  n:齿轮的齿数,r1齿轮半径，r2内圆比例
	createGear(n=12,r1=50,r2=0.8){
		let gear=this.createPolygon({sx:1,sy:1,color:'#00ff00'});
		let [sides,maxs,mins,angle,s]=[[],[],[],0,1];
		n*=2;
		for (let i=0; i <= n; ++i) {
			s=i%2==0?1:-1;
			maxs.push([(Math.sin(angle+.1*s)*r1),(Math.cos(angle+.1*s)*r1)]);
			mins.push([(Math.sin(angle)*r1*r2),(Math.cos(angle)*r1*r2)]);
			angle += 2*Math.PI/n;
		}
		for(let i=0;i<n;i+=2){
			sides.push(maxs[i],maxs[i+1]);
			if(i<n-2){
				sides.push(mins[i+1],mins[i+2]);
			}else{
				sides.push(mins[n-1],mins[0]);
				sides.push(mins[n],maxs[0]);
			}		
		}
		gear.setSides(sides);
		return gear;
	}
	createPolygon({sx=0.5,sy=0.5,color='#00ff00'}){
		let polygon=this.createDisplay('polygon');
		polygon.setColor(color).setScaleXY(sx,sy);
		return polygon
	}
	createRect(w,h,c,x=0,y=0){
		return this.createDisplay('rect').setWH(w,h).setXY(x,y).setColor(c);
	}
	createFish1({sx=0.5,sy=0.5,color='#00ff00'}){//创建小鱼1
		return this.createPolygon({sx,sy,color}).setSides([[-12,-47],[35,3],[-19,51],[-8,28],[-38,10],[-68,37],[-56,2],[-67,-28],[-37,-5],[-7,-23],[-12,-47]]);
	}
	createFish2({sx=0.5,sy=0.5,color='#00ff00'}){//创建小鱼2
		return this.createPolygon({sx,sy,color}).setSides([[-4, -33], [38, 1], [-3, 36], [-58, 7], [-90, 36], [-81, 3], [-91, -30], [-58, -4], [-4, -33]]);
	}
	createFish3({sx=0.5,sy=0.5,color='#00ff00'}){//创建小鱼3
		return this.createPolygon({sx,sy,color}).setSides([[-22,-36],[28,-2],[-22,41],[-20,1],[-47,22],[-47,-16],[-20,0],[-22,-36]]);
	}
	createShark({sx=0.5,sy=0.5,color='#00ff00'}){//创建鲨鱼
		return this.createPolygon({sx,sy,color}).setSides([[45,-33],[100,2],[45,8],[68,19],[3,28],[-64,12],[-97,6],[-135,16],[-119,-2],[-151,-27],[-95,-15],[-59,-19],[-18,-27],[-29,-51],[12,-34],[45,-33]]);
	}
	createStone({radius=25,num=10,color='#00ff00'}){//创建石头
		let [a,f,sides,mPI]=[0,{},[],2*Math.PI];
		for (let i=0; i <= num; ++i) {
			a+= Math.random()*(2*mPI/num);
			a=a>mPI?mPI:a;
			let r=radius+Math.random()*10;
			if(i==0){
				f['a']=a;
				f['r']=r;
			}else if(i==num){
				a=f.a;
				r=f.r;
			}
			sides.push([parseInt(r * Math.sin(a)),parseInt(r * Math.cos(a))]);
		}
		return this.createPolygon({sx:1,sy:1,color}).setSides(sides);
	}
	/**画水果皮*/
	drawFruitSkin(r,c1,c2){
		let node=this.createDisplay('circle')
		let bg=this.createDisplay('circle').setRadius(r).setColor(c1);
		let mid=this.createDisplay('circle').setRadius(r-5).setColor(c2);
		node.addChild(bg);
		node.addChild(mid);
		return node;
	}
	/**画西瓜*/
	drawWatermelon(r=50,c1='#006600',c2='#FFE1E2',c3='#FF0000') {
		let node=this.drawFruitSkin(r,c1,c2)
		let value=this.createDisplay('circle').setRadius(r-10).setColor(c3);
		node.addChild(value);
        for (let i = 0; i < 8; i++) {
            let a1=this.angleToRadian(i * 45);
            let r1=r*0.6;
            let [x,y]=[Math.cos(a1)*r1,Math.sin(a1)*r1];
			let v=this.createDisplay('circle').setRadius(2).setColor('#000').setXY(x,y);
			node.addChild(v);
        }
		node.addChild(this.createDisplay('circle').setRadius(.1))//最后一个看不见却有特殊作用
		return node;
    }
	/**画橘子*/
	drawOrange(r=50,c1='#E1A73C',c2='#FEF6B6',c3='#FFCC00',gap=10) {
		let node=this.drawFruitSkin(r,c1,c2)
		for (let i = 0; i < 8; i++) {
			let [a1,a2]=[(i * 45), (i * 45 + 40)]
			let v=this.createDisplay('arc').setRadius(r-gap).setColor(c3).setArcSarEnd(a1,a2)
			node.addChild(v);
		}
		node.addChild(this.createDisplay('circle').setRadius(.1))//最后一个看不见却有特殊作用
		return node;
	}
	/**画猕猴桃*/
	drawKiwiFruit(r=50,c1='#006600',c2='#85D927',c3='#006600',c4='#E6FC9A') {
		let node=this.drawFruitSkin(r,c1,c2)
		let value=this.createDisplay('circle').setRadius(r*0.4).setColor(c4);
		node.addChild(value);
		for (let i = 0; i < 8; i++) {
			let a1=this.angleToRadian(i * 45);
            let r1=r*0.55;
            let [x,y]=[Math.cos(a1)*r1,Math.sin(a1)*r1];
			let v=this.createDisplay('circle').setRadius(2).setColor(c3).setXY(x,y);
			node.addChild(v);
		}
		node.addChild(this.createDisplay('circle').setRadius(.1))//最后一个看不见却有特殊作用
		return node;
	}
	/**百香果*/
	drawPassionFruit(r=50,c1='#9E3D65',c2='#FFF6D2',c3='#FFC114',c4='#CE9200',znum=30) {
		let [a1,r1]=[0,r*0.8]
		let node=this.drawFruitSkin(r,c1,c2);
		let value=this.createDisplay('circle').setRadius(r1).setColor(c3);
		node.addChild(value);
		for (let i = 0; i < znum; i++) {
			a1+=72
			var r2 = r1*(Math.floor(a1/360)+1)*0.12;
			r2=r2>r1?(r1/2+Math.random()*r1/2):r2
			let [x,y]=[Math.cos(a1)*r2,Math.sin(a1)*r2];
			let v=this.createDisplay('circle').setRadius(2).setColor(c4).setXY(x,y);
			node.addChild(v);
		}
		node.addChild(this.createDisplay('circle').setRadius(.1))//最后一个看不见却有特殊作用
		return node;
	}
	/**画山竹*/
	drawMangosteen(r1=50,r2=12){
		return this.drawOrange(r1,'#5C2F32','#CD544B','#FFFFFF',r2);
	}
	/**火龙果*/
	drawPitaya(r1=50){
		return this.drawPassionFruit(r1,'#D32952','#FFFFFF','#FFFFFF','#000000',50);
	}
	/**画时钟*/
	drawClock(r=50,hour=6,minute=20,c1='#000',c2='#fff',c3='#000') {
		let node=this.drawFruitSkin(r,c1,c2)
		let value=this.createDisplay('circle').setRadius(3).setColor(c3);
		node.addChild(value);
		let pos=[1,2]
		for (let i = 0; i < 60; i++) {
            let a1=this.angleToRadian(i * 6);
            let r1=r-10;
            let [x,y]=[Math.cos(a1)*r1,Math.sin(a1)*r1];
			let p=pos[0];
			if(i%5==0)	p=pos[1];
			let v=this.createDisplay('circle').setRadius(p).setColor(c3).setXY(x,y);
			node.addChild(v);
        }
		let lens=[r*0.7,r*0.9];
		for(let i=0;i<2;i++){
			let a1=i==0?hour*30:minute*6;
			if(i==0){
				a1+=30/(60/minute);
			}
			a1=this.angleToRadian(a1-90);//-90是因为从水平方向改为竖直方向
			let r1=lens[i];
            let [x,y]=[Math.cos(a1)*r1,Math.sin(a1)*r1];
			let li=this.createDisplay('line').setWH(x,y).setColor(c3);
			li.lineWidth=pos[1-i];
			node.addChild(li);
		}
		node.addChild(this.createDisplay('circle').setRadius(.1));//最后一个看不见却有特殊作用
		return node;
	}
		/**画进度条*/
		drawProgress(w,h,c1,c2){
			let node=this.createDisplay('rect').setWH(w,h).setColor(c1);
			let bar=this.createDisplay('rect').setWH(w,h).setColor(c2);
			node.setAnchorXY(0,0);
			bar.setAnchorXY(0,0);
			node.bar=bar;
			node.addChild(bar);
			node.addChild(this.createDisplay('circle').setRadius(.1));//最后一个看不见却有特殊作用
			return node;
		}
	/**---简单的Tween动画----------*/
	to=(item,data,time,callBack)=>{
		let values={};
		for(let i in data){
			let num=data[i]-item[i];
			num=num/(time/16.6);
			values[i]=num;
		}
		this.loop(item,values,time,callBack);
	}
	by=(item,data,time,callBack)=>{
		let values={};
		for(let i in data){
			let num=data[i];
			num=num/(time/16.6);
			values[i]=num;
		}
		this.loop(item,values,time,callBack);
	}
	//外部不使用此方法
	loop=(item,values,time,callBack)=>{
		let [hz,count]=[16.6,0];
		function loop(){
			if(count<time){
				for(let i in values){
					item[i]+=values[i];
				}
				count+=hz;
				setTimeout(loop,hz);
			}else{
				callBack&&callBack(item);
			}
		}
		loop();
	}
	/**-------------*/
}